const { Sequelize, Model } = require("sequelize");
const { db } = require("../core/db");

class Comments extends Model {
  static async addComment(book_id, content) {
    const comment = await Comments.findOne({
      where: {
        book_id,
        content,
      },
    });
    if (!comment) {
      await Comments.create({ book_id, content, nums: 1 });
    } else {
      await comment.increment("nums", { by: 1 });
    }
  }

  static async getComment(book_id, start, count) {
     const common =  await Comments.findAll({
      where: {
        book_id,
      },
      limit: count,
      offset: start,
    });
    return common
  }
}

Comments.init(
  {
    content: Sequelize.STRING,
    nums: {
      type: Sequelize.INTEGER,
      defaultValue: 0,
    },
    book_id: Sequelize.INTEGER,
  },
  {
    sequelize: db,
    tableName: "comment",
  }
);

module.exports = {
  Comments,
};
